﻿using HMS.Contracts.Models;
using HMS.Core.Abstractions;
using HMS.Core.DataProtocol;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

namespace HMS.Controllers;

[ApiController]
[Route("[controller]")]
public class TenantController : ControllerBase
{
    private readonly ITenantService _service;

    public TenantController(ITenantService service)
    {
        _service = service;
    }

    [HttpPost]
    public async Task<OperationalResult<Token>> LoginAsync([FromBody] TenantLoginModel model)
    {
        var result = await _service.AuthenticateAsync(model, HttpContext.RequestAborted);

        if (result.Status == OperationalResult.SUCCESS)
        {
            var claims = new[]
            {
                new Claim("name", result.Data.Tenant.Name),
                new Claim("tenant", result.Data.Tenant.TenantId)
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var user = new ClaimsPrincipal(claimsIdentity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

            HttpContext.Response.Cookies.Append("tenant", result.Data.Tenant.TenantId, new Microsoft.AspNetCore.Http.CookieOptions
            {
                Secure = true,
                HttpOnly = true
            });
        }

        return result;
    }
}